package com.cci.kangdao.service.impl;


import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.BusinessRegionTDao;
import com.cci.kangdao.dao.CustomerEngineRelDao;
import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.BusinessService;
import com.cci.kangdao.service.CSUService;
import com.cci.kangdao.service.SendSMSLogService;
import com.cci.kangdao.utilTool.*;
import com.gexin.fastjson.JSON;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("CSUService")
public class CSUServiceImpl implements CSUService {

	private Logger log = Logger.getLogger(this.getClass().getName());
	@Autowired
	private RedisClientUtils redisClientUtils;
	@Autowired
	private SendSMSLogService sendSMSLogService;
	@Resource
	private UserTDao userTDao;
	@Resource
	private CustomerEngineRelDao customerEngineRelDao;


	//通过esn获取用户相关信息
	public ModelAndView getUserInfoByESNCSU(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		Map<String,Object> contentJsonMap = JSON.parseObject(MapUtils.getString(map,"contentJson"), Map.class);
		try{
			JSONObject obj = new JSONObject();  //声明返给前端json对象
			if(!contentJsonMap.containsKey("EngineMsgList")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "发动机信息不能为空！");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			List<Map<String,Object>> enginMsgList = (List<Map<String,Object>>)contentJsonMap.get("EngineMsgList");
			List<Map<String,Object>> userInfoList = new ArrayList<>();
			String esns = "";   //esn字符串  逗号分隔
			if(CollectionUtils.isNotEmpty(enginMsgList)){
				for(Map<String,Object> enginMsg : enginMsgList){
					String esn = MapUtils.getString(enginMsg,"ESN","");
					esns += esn+",";
				}
				if(esns.endsWith(",")){
					esns = esns.substring(0,esns.length()-1);
				}
			}
			if(StringUtils.isNotEmpty(esns)){
				userInfoList = customerEngineRelDao.getUserInfoByEsns(esns);
			}
			JSONObject jb = new JSONObject();
			jb.put("list",userInfoList);
			obj.put("data", jb);
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//手机发送验证码
    @Transactional
	@Override
	public ModelAndView sendVerifyCodeByPhoneCSU(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		Map<String,Object> contentJsonMap = JSON.parseObject(MapUtils.getString(map,"contentJson"), Map.class);
		try{
			JSONObject obj = new JSONObject();  //声明返给前端json对象
			if(!contentJsonMap.containsKey("userPhone")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "用户手机号不能为空！");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			String userPhone = MapUtils.getString(contentJsonMap,"userPhone","");
			if(userTDao.checkUserByPhone(userPhone) <= 0){
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "用户不存在!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			generateSmsCode(userPhone,"6");
			obj.put("data", "");
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//校验手机号和验证码是否有效
	@Override
	public ModelAndView checkVerifyCodePhoneStatusCSU(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		Map<String,Object> contentJsonMap = JSON.parseObject(MapUtils.getString(map,"contentJson"), Map.class);
		try{
			JSONObject obj = new JSONObject();  //声明返给前端json对象
			if(!contentJsonMap.containsKey("userPhone")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "用户手机号不能为空！");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			if(!contentJsonMap.containsKey("verificationCode")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "验证码不能为空！");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			String userPhone = MapUtils.getString(contentJsonMap,"userPhone","");
			String verificationCode = MapUtils.getString(contentJsonMap,"verificationCode","");
			String redisCode = redisClientUtils.get("smsCSU" + userPhone);
			log.info(redisCode);
			if (StringUtils.isEmpty(redisCode) || !verificationCode.equals(redisCode)) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "当前手机号码与验证码不匹配！");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			obj.put("data", "");
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			log.error(e.getMessage(),e);
		}
		return null;
	}



	private void generateSmsCode(String mobile,String type){
		//随机生成验证码
		String smsCode = PublicTool.getFourRandom();
		log.info("您的验证码是" + smsCode);
		//1分钟有效,但是实际是时间太短
		redisClientUtils.set("smsCSU" + mobile, smsCode, 90);
		//拼装短信内容
		String smstext = "您此次的验证码为{验证码}，有效期1分钟，请输入后进行验证，谢谢！";
		// 发送验证码
		String reuslt = SmsUtils.sendMessage(mobile, smstext.replace("{验证码}", smsCode));
		//sendSMSLogService.insertSendSMSLog   type为6代表csu项目获取验证码
		sendSMSLogService.insertSendSMSLog(1, type, mobile, smstext.replace("{验证码}", smsCode), reuslt);



	}
}
